from sqlalchemy import delete, insert, select

from forward.dependencies.database import db
from forward.model.orm.base import BaseORM
from forward.model.schemas.admin import AdminOutSchema
from forward.model.tables.system import SystemAuthAdminModel as AdminModel
from forward.model.tables.user import AdminUserModel


class AdminORM(BaseORM):
    MODEL = AdminModel
    OUT_SCHEMA = AdminOutSchema

    async def relate_admin_user(self, admin_id, user_id):
        """
        关联管理员用户
        """
        statement = insert(AdminUserModel).values(admin_id=admin_id, user_id=user_id)
        return await db.execute(statement)

    async def unrelate_admin_users(self, admin_id):
        """
        取消关联管理员用户
        """
        statement = delete(AdminUserModel).where(AdminUserModel.admin_id == admin_id)
        return await db.execute(statement)

    async def get_one_by_user_id(self, user_id) -> AdminOutSchema | None:
        statement = (
            select(AdminModel)
            .select_from(AdminModel)
            .join(AdminUserModel, AdminUserModel.admin_id == AdminModel.id)
            .where(AdminUserModel.user_id == user_id)
        )
        record = await db.fetch_one(statement)
        if not record:
            return None
        return AdminOutSchema.model_validate(record, from_attributes=True)
